var _nav = null;
window.addEvent('domready', function(){
	_nav = new Nav();
});

var Nav = new Class({
	Implements: [Events, Options],

	options: {
		fadeDuration: 500, // 500
		loadingDuration: 1500, // 1500
		goToPanelDuration: 500, // 700
		switchContentDuration: 700, // 700
		goToSectionDuration: 500
	},

	initialize: function (options) {
		if($$('#prehome')[0].length == 0)
			return;

		this.setOptions(options);
		this.global = $('global');
		this.prehome = $('prehome');
		this.prehomeLoading = this.prehome.getElements('.loading')[0];
		this.prehomePercent = this.prehomeLoading.getElements('.percent')[0];

		this.pages = $('pages');

		this.panelsContainer = $$('#contents .container')[0];
		this.panels = this.panelsContainer.getElements('.panel');
		this.contents = this.panelsContainer.getElements('.content');

		this.currentContent = this.contents.filter('.current')[0];
		this.currentPanel = this.currentContent.getParents('.panel')[0];

		this.fxScroll = new Fx.Scroll(window, {
			duration: this.options.goToSectionDuration
		});

		this.buildPrehome();
		this.buildLinks();
		this.buildNav();
		this.buildDecrypt();

		this.resize();
	},

	buildDecrypt: function(){
		$$('.decrypt').each(function(el){
			el.set('text', decrypt(el.get('text')));
		}.bind(this));

		$$('.decrypt_href').each(function(el){
			el.set('href', decrypt(el.get('href')));
		}.bind(this));
	},

	buildLinks: function(){
		$$('a.scroll_section').each(function(a){
			a.addEvent('click', function(e){
				e.stop();
				this.goToSection(a.get('rel'));
			}.bind(this));
		}.bind(this));

		/*$$('a.scroll_panel').each(function(a){
			a.addEvent('click', function(e){
				e.stop();
				this.goToContent(a.get('rel'));
			}.bind(this));
		}.bind(this));*/
	},

	buildPrehome: function(){
		if(Cookie.read('gh') == 'true'){
			this.prehome.setStyle('display', 'none');
			this.pages.setStyle('display', 'block');
		}
		else {
			Cookie.write('gh', 'true');
			window.addEvent('touchstart', function(event){
				event.preventDefault();
			}.bind(this));

			this.global.setStyles({
				'height': window.getHeight(),
				'overflow' : 'hidden'
			});

			this.prehome.store('fx', new Fx.Morph(this.prehome, {
				link: 'cancel',
				duration: this.options.fadeDuration
			}));

			this.pages.setStyles({
				'display' : 'block',
				'opacity' : 0
			});
			this.pages.store('fx', new Fx.Morph(this.pages, {
				link: 'cancel',
				duration: this.options.fadeDuration
			}));

			this.prehomeLoading.setStyles({
				'display' : 'block',
				'opacity' : 0
			});
			this.prehomeLoading.store('fx', new Fx.Morph(this.prehomeLoading, {
				link: 'cancel',
				duration: this.options.fadeDuration/2
			}));

			new Asset.images([this.prehomeLoading.getElement('.mask').getStyle('background-image').replace(/^url\(["']?/, '').replace(/["']?\)$/, '')], {
				onComplete: function(){
					this.prehomeLoading.retrieve('fx').start({
						'opacity': 1
					}).chain(function(){
							document.documentElement.scrollTop = 0;
							document.body.scrollTop = 0;
							this.loadPrehome();
						}.bind(this));
				}.bind(this)
			});
		}
	},

	loadPrehome: function(){
		new Fx.Morph(this.prehomePercent, {
			link: 'cancel',
			duration: this.options.loadingDuration,
			onComplete:function(){
				this.hidePrehome();
			}.bind(this)
		}).start({
				'width': this.prehomeLoading.getSize().x
			});
	},

	hidePrehome: function(){
		this.prehome.retrieve('fx').start({
			'opacity': 0
		}).chain(function(){
				this.prehome.setStyles({
					'display' : 'none',
					'opacity' : 1
				});
				this.showPages();
				window.removeEvents('touchstart');
			}.bind(this));
	},

	showPages: function(){
		this.global.setStyles({
			'height': 'auto',
			'overflow' : 'visible'
		});

		this.pages.retrieve('fx').start({
			'opacity': 1
		});
	},

	buildNav: function(){
		this.panelsContainer.store('fx', new Fx.Morph(this.panelsContainer, {
			link: 'cancel',
			duration: this.options.goToPanelDuration
		}));

		this.contents.each(function(content){
			content.store('fx', new Fx.Morph(content, {
				link: 'cancel',
				duration: this.options.switchContentDuration
			}));
		}.bind(this));

		window.addEvent('resize', function(){
			this.resize();
		}.bind(this));
	},

	resize: function(){
		var width = window.getWidth();
		this.panels.setStyle('width', width);
		this.panelsContainer.setStyles({
			'width':width*this.panels.length,
			'margin-left': -width*this.panels.indexOf(this.currentPanel)
		});
		this.setHeightContainer(this.currentContent);
	},

	goToPanel: function(panel, callback){
		panel = $$('#'+panel);
		if(panel.length == 0)
			return;
		panel = panel[0];

		var myFx = new Fx.Scroll(window).toTop();

		var index = this.panels.indexOf(panel);
		this.panelsContainer.retrieve('fx').start({
			'margin-left': -index*panel.getWidth()
		}).chain(function(){
			this.currentPanel = panel;
			if(callback != undefined)
				callback();
		}.bind(this));
	},

	goToContent: function(content){
		content = $$('#'+content);
		if(content.length == 0)
			return;
		content = content[0];
		if(content == this.currentContent)
			return;

		var panel = content.getParents('.panel')[0];

		var panelId = panel.get('id');
		var currentPanelId = this.currentPanel.get('id');

		this.setHeightContainer(content);

		if(panelId.contains(currentPanelId)){
			this.currentContent.retrieve('fx').start({
				'opacity': 0
			}).chain(function(){
				this.currentContent.removeClass('current');
				this.currentContent.setStyles({
					'opacity':1
				});

				this.currentContent = content;

				this.currentContent.setStyles({
					'opacity': 0,
					'display': 'block'
				});

				this.currentContent.retrieve('fx').start({
					'opacity': 1
				}).chain(function(){
					this.currentContent.addClass('current');
					this.currentContent.set('style', '');
				}.bind(this));
			}.bind(this));
		}
		else{
			content.addClass('current');
			this.goToPanel(panel.get('id'), function(){
				this.currentContent.removeClass('current');
				this.currentContent = content;
				this.resize();
			}.bind(this));
		}
	},

	setHeightContainer: function(content){
	/*var contentSize = content.measure(function(){
			return this.getDimensions();
		});
		this.panelsContainer.setStyle('height', contentSize.height);*/
	},

	goToSection: function(section){
		section = $$('#'+section);
		if(section.length == 0)
			return;
		section = section[0];

		this.fxScroll.toElement(section);
	}
});

function isDesktop(){
	return (window.matchMedia) ? !window.matchMedia('(max-width:800px)').matches : true;
}

function decrypt(string){
	var length = string.length;
	if(length % 2 == 1)
		string = string.substr(0, 1)+' '+string.substr(1, length-1);
	return trim(str_split(string, 2).reverse().join(''));
}

function trim(string)
{
	return string.replace(/^\s+/g,'').replace(/\s+$/g,'')
}

function str_split(string, split_length) {
	if (split_length === null) {
		split_length = 1;
	}
	if (string === null || split_length < 1) {
		return false;
	}
	string += '';
	var chunks = [],
		pos = 0,
		len = string.length;
	while (pos < len) {
		chunks.push(string.slice(pos, pos += split_length));
	}
	return chunks;
}